package com.are.inventario;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

public class PlacaActivity extends Activity implements OnClickListener {

	private EditText codigo,matricula,peso,pesoliquido,anio,pais;
	private TextView latitud,longitud;
	private MenuItem mFoto,mAdd, mUpdate, mNew,mFind;
	private RadioButton existente;
	
	
	private ProgressDialog progressDialog;
	private String ReceiveServer = "";
	
	private static final int MODE_NEW = 1;
	private static final int MODE_UPDATE = 2;
	private static final int INTENT_PAISES = 101;
	
	private String parametros;
	private String url;
	
	
	private int mode = MODE_NEW;
	private String key = "";  // variable Key para actualizar
	
	private final Handler progressHandler = new Handler() {

		public void handleMessage(Message msg) {
			if (msg.obj != null) {
				ReceiveServer = (String) msg.obj;
				ShowMensaje(ReceiveServer);
			}
			progressDialog.dismiss();
		}
	};
	
	private static final int INTENT_ID_GPS = 100;
	private static final int INTENT_ID_FIND = 102;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.placa_activity);
		
		latitud = (TextView)findViewById(R.id.lbLatitud);
		longitud = (TextView)findViewById(R.id.lbLongitud);
		codigo = (EditText)findViewById(R.id.CodigoPlaca);
		matricula = (EditText)findViewById(R.id.MatriculaPlaca);
		peso = (EditText)findViewById(R.id.Peso);
		pesoliquido = (EditText)findViewById(R.id.PesoLiquido);
		anio = (EditText)findViewById(R.id.Anio);
		pais = (EditText)findViewById(R.id.Pais);
		pais.setEnabled(false);
		existente = (RadioButton)findViewById(R.id.ExistentePlaca);
		
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.placa_activity, menu);
		mFoto = menu.findItem(R.id.menu_placa_image);
		mUpdate = menu.findItem(R.id.menu_placa_update);
		mAdd = menu.findItem(R.id.menu_placa_add);
		mNew = menu.findItem(R.id.menu_placa_new);
		mFind = menu.findItem(R.id.menu_placa_find);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
			case R.id.menu_placa_add:
				mode = MODE_NEW;
				SaveRecord();
			break;
			case R.id.menu_placa_new:
				Limpiar();
				break;
			case R.id.menu_placa_update:
				mode = MODE_UPDATE;
				SaveRecord();
				break;
			case R.id.menu_placa_image:
				Intent intentCamera = new Intent(PlacaActivity.this,
						Camera.class);
				intentCamera.putExtra("key", this.key);
				intentCamera.putExtra("tipo", "2");
				startActivity(intentCamera);
				break;
			case R.id.menu_placa_find:
				startActivityForResult(new Intent(this, BuscarPlacaActivity.class),INTENT_ID_FIND);
				break;
			case R.id.menu_placa_pais:
		            startActivityForResult(new Intent(PlacaActivity.this,
			                  PaisActivity.class), INTENT_PAISES);
				break;
			case R.id.menu_placa_gps:
				Intent intent = new Intent(this, GPSActivity.class);
				startActivityForResult(intent,INTENT_ID_GPS);
			break;
		}
		
		return true;
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch(requestCode) {
			case INTENT_ID_GPS:
				latitud.setText(data.getStringExtra("latitud"));
				longitud.setText(data.getStringExtra("longitud"));
				break;
			case INTENT_PAISES:
				pais.setText(data.getStringExtra("pais"));
				break;
				
			case INTENT_ID_FIND:
				codigo.setText(data.getStringExtra("codigo"));
				matricula.setText(data.getStringExtra("matricula"));
				peso.setText(data.getStringExtra("peso"));
				pesoliquido.setText(data.getStringExtra("liquido"));
				anio.setText(data.getStringExtra("anio"));
				pais.setText(data.getStringExtra("pais"));
				longitud.setText(data.getStringExtra("longitud"));
				latitud.setText(data.getStringExtra("latitud"));
				RefreshMenu();
				
				break;
			
			}
		}
		
	}
	
	private void ShowMensaje(String data) {
		if (data.equals("OK")) {
			AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta("Placa guardada correctamente");
			alert.show();
			switch(mode) {
			case MODE_NEW:
				RefreshMenu();
				break;
			case MODE_UPDATE:
				
				break;
			}
			
			
		} else { // error al confirmar la orden
			AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta(data);
			alert.show();
		}

	}
	
	private Dialog crearDialogoAlerta(String mensaje) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Informacion");
		builder.setMessage(mensaje);
		builder.setCancelable(false);
		builder.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});		
		return builder.create();
	}
	
	public void SaveRecord() {
		String strCodigo = codigo.getText().toString();
		String strMatricula = matricula.getText().toString();
		String strPeso = peso.getText().toString();
		String strPesoLiquido = pesoliquido.getText().toString();
		String strAnio = anio.getText().toString();
		String strPais = pais.getText().toString(); 
		String strLongitud = longitud.getText().toString();
		String strLatitud = latitud.getText().toString();
		String strTipo ="2"; // Nuevo
		if (existente.isChecked()) {
			strTipo = "1";
		}
		
		if ( strCodigo.equals("") || strMatricula.equals("") || strPeso.equals("") || strPesoLiquido.equals("") 
				|| strAnio.equals("") || strPais.equals("") || strLongitud.equals("") 
				|| strLatitud.equals("") ) {
			AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta("Falta Informacion, verifique porfavor");
			alert.show();
			return;
		}
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String imei = tm.getDeviceId();
        
		try {
			parametros =  URLEncoder.encode("codigo", "ISO-8859-1") + "=" + URLEncoder.encode(strCodigo, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("matricula", "ISO-8859-1") + "=" + URLEncoder.encode(strMatricula, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("peso", "ISO-8859-1") + "=" + URLEncoder.encode(strPeso, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("peso_liquido", "ISO-8859-1") + "=" + URLEncoder.encode(strPesoLiquido, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("anio", "ISO-8859-1") + "=" + URLEncoder.encode(strAnio, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("pais", "ISO-8859-1") + "=" + URLEncoder.encode(strPais, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("longitud", "ISO-8859-1") + "=" + URLEncoder.encode(strLongitud, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("latitud", "ISO-8859-1") + "=" + URLEncoder.encode(strLatitud, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("imei", "ISO-8859-1") + "=" + URLEncoder.encode(imei, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("tipo", "ISO-8859-1") + "=" + URLEncoder.encode(strTipo, "ISO-8859-1");
			
			LoadData();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta(e.getMessage());
			alert.show();
		}
		
		
	}
	
	private void LoadData() {
		progressDialog = ProgressDialog.show(PlacaActivity.this, "",
				"Por favor espere mientras se envian los datos...", true);

		this.url = "http://siscos.fcr.com.co:8080/AreApp/SrvPlaca?";
		switch(mode) {
		case MODE_NEW:
			url += "operacion=add";
			break;
		case MODE_UPDATE:
			try {
				url += "operacion=modify&key=" + URLEncoder.encode(this.key, "ISO-8859-1");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta(e.getMessage());
				alert.show();
				return;
			}
		}
		new Thread(new Runnable() {
			public void run() {
				HttpConection conn = new HttpConection(url,parametros);
				Message msg = progressHandler.obtainMessage();
				msg.obj = conn.Send();
				progressHandler.sendMessage(msg);
			}
		}).start();
	}
	
	private void Limpiar() {
		codigo.setText("");
		matricula.setText("");
		peso.setText("");
		pesoliquido.setText("");
		anio.setText("");
		pais.setText("");
		longitud.setText("");
		latitud.setText("");
		mFoto.setEnabled(false);
		mUpdate.setEnabled(false);
		mAdd.setEnabled(true);
		codigo.setEnabled(true);		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	private void RefreshMenu() {
		mFoto.setEnabled(true);
		mUpdate.setEnabled(true);
		mAdd.setEnabled(false);
		codigo.setEnabled(false);
		mNew.setEnabled(true);
		this.key = codigo.getText().toString();  // Identificador para las actualizaciones
		mode = MODE_UPDATE;
	}

}
